import 'package:flutter/material.dart';

//宽高动画封装
class ExpandedSection extends StatefulWidget {
  final Widget child;
  final bool expand;
  var axis = Axis.horizontal;
  double axisAlignment = 0;
  Duration? time;
  ExpandedSection({
    this.expand = false,
    required this.child,
    this.axis = Axis.vertical,
    this.axisAlignment = 0,
    this.time = const Duration(milliseconds: 300),
  });

  @override
  _ExpandedSectionState createState() => _ExpandedSectionState();
}

class _ExpandedSectionState extends State<ExpandedSection> with SingleTickerProviderStateMixin {
  late AnimationController expandController;
  late Animation<double> animation;

  @override
  void initState() {
    super.initState();
    prepareAnimations();
  }

  ///Setting up the animation
  void prepareAnimations() {
    expandController = AnimationController(vsync: this, duration: widget.time);
    Animation<double> curve = CurvedAnimation(
      parent: expandController,
      curve: Curves.linear,
    );
    animation = Tween(begin: 0.0, end: 1.0).animate(curve)
      ..addListener(() {
        setState(() {});
      });
  }

  @override
  void didUpdateWidget(ExpandedSection oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.expand) {
      expandController.forward();
    } else {
      expandController.reverse();
    }
  }

  @override
  void dispose() {
    expandController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SizeTransition(
      axisAlignment: widget.axisAlignment,
      sizeFactor: animation,
      axis: widget.axis,
      child: widget.child,
    );
  }
}
